package com.mike.uaa.jackson;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.mike.uaa.core.DefaultAuthenticationToken;
import com.mike.uaa.core.GrantedAuthority;
import com.mike.uaa.core.SimpleGrantedAuthority;
import com.mike.uaa.core.User;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author z zhang
 */
public class DefaultAuthTokenDeserializer extends JsonDeserializer<DefaultAuthenticationToken> {

    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public DefaultAuthenticationToken deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException {
        JsonNode rootNode = jsonParser.getCodec().readTree(jsonParser);

        JsonNode userNode = rootNode.get("user");

        User user = User.builder().id(userNode.get("id") != null ? userNode.get("id").asInt() : null)
                .username(userNode.get("username") != null ? userNode.get("username").asText() : null)
                .nickname(userNode.get("nickname") != null ? userNode.get("nickname").asText() : null)
                .status(userNode.get("status") != null ? userNode.get("status").asInt() : null)
                .mobile(userNode.get("mobile") != null ? userNode.get("mobile").asText() : null)
                .lastLogin(userNode.get("lastLogin") != null ? parse(userNode) : null)
                .build();


        JsonNode authorityNode = rootNode.get("authority");

        List<GrantedAuthority> authorities = new ArrayList<>();
        if (authorityNode != null && authorityNode.isArray()) {
            for (JsonNode roleNode : authorityNode) {
                authorities.add(SimpleGrantedAuthority.of(roleNode.asText())); // 转换为小写
            }
        }

        boolean authenticated = rootNode.get("authenticated") != null && rootNode.get("authenticated").asBoolean();

        // 使用构建器创建对象
        return DefaultAuthenticationToken.builder()
                .principal(user)
                .tokenValue(rootNode.get("tokenValue") != null ? rootNode.get("tokenValue").asText() : null)
                .issuedAt(rootNode.get("issuedAt") != null ? Instant.ofEpochMilli(rootNode.get("issuedAt").asLong()) : null)
                .expiresIn(rootNode.get("expiresIn") != null ? rootNode.get("expiresIn").asLong() : -1)
                .authorities(authorities)
                .authenticated(authenticated)
                .build();
    }


    private LocalDateTime parse(JsonNode userNode) {
        return LocalDateTime.parse(userNode.get("lastLogin").asText(), formatter);
    }
}
